package com.topisv.tms.rest.qimen.qmsend;

import java.io.StringReader;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXB;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.topisv.tms.entity.qimen.QmResendInfo;
import com.topisv.tms.rest.qimen.qmentity.response.QMReponse;
import com.topisv.tms.rest.qimen.qmservice.QmResendInfoService;
import com.topisv.tms.rest.qimen.request.RequestParams;
import com.topisv.tms.slf4j.MarkerConstant;
import com.topisv.tms.utils.InitProperties;
import com.topisv.tms.utils.mail.MailSenderInfo;

/**
 * 奇门发送失败消息重发 Date Author Version Description
 * ---------------------------------------------------------- 2015-7-7 GH 1.0 Create
 */
@Component
@Lazy(false)
public class QmResendInfoProvider {
    private static final Logger logger = LoggerFactory.getLogger(QmResendInfoProvider.class);

    @Autowired
    private QmResendInfoService service;

    @Async
    @Scheduled(cron = "0 0/1 * * * *")
    public void executor() {
        if (!"1".equals(InitProperties.get("qm.resend.flag"))) {
            return;
        }
        try {
            int msg = 0;
            List<QmResendInfo> qriList = service.findBySendResultAndResendCount();
            for (QmResendInfo qri : qriList) {
                qri.setLockTask("lock");
            }
            if (qriList.size() > 0) {
                service.save(qriList);
                logger.info(MarkerConstant.QIMEN_MARKER, "奇门重发开始,重发数量: [{}]", qriList.size());

                for (QmResendInfo qri : qriList) {
                    String dealIp = InetAddress.getLocalHost().getHostAddress();
                    qri.setDealIp(dealIp);
                    qri.setResendCount(qri.getResendCount() + 1);
                    qri.setResendTime(new Date());
                    qri.setSendResult("do");

                    try {
                        String result = "";
                        RequestParams sendParams = new RequestParams();
                        Map<String, String> paramMap = sendParams.getParams();
                        paramMap.put("method", qri.getMethod());
                        paramMap.put("format", qri.getFormat());
                        paramMap.put("app_key", qri.getAppKey());
                        paramMap.put("v", qri.getV());
                        paramMap.put("sign_method", qri.getSignMethod());
                        paramMap.put("customerId", qri.getCustomerId());
                        String sendBody = qri.getSendContent();
                        sendParams.setRequestXml(sendBody);
                        sendParams.setSecret(qri.getSecret());

                        Map<String, String> otherParams = new HashMap<String, String>();
                        otherParams.put("customerCode", qri.getCustomerId());
                        String sendUrl = QmRequestSender.getSendUrl(sendParams);
                        logger.info(MarkerConstant.QIMEN_MARKER, "奇门重发URL{}", sendUrl);

                        String responseXml = QmRequestSender.pub2(sendUrl, sendBody);
                        logger.info(MarkerConstant.QIMEN_MARKER, "响应报文:" + responseXml);

                        QMReponse qmp = JAXB.unmarshal(new StringReader(responseXml), QMReponse.class);
                        if ("success".equals(qmp.getFlag())) {
                            result = "success";
                        } else {
                            result = "failure";
                            qri.setSendResult("undo");
                        }
                        // logger.info("奇门重试结果 Flag:"+result+"("+qmp.getFlag()+")
                        // Code:"+qmp.getCode()+" Message:"+qmp.getMessage()+" xml:"+responseXml);
                    } catch (Exception e) {
                        logger.info(MarkerConstant.QIMEN_MARKER, "奇门重试失败 [{}] 次", qri.getResendCount());
                        qri.setSendResult("undo");
                    }
                    if (qri.getResendCount() >= 5 && !"do".equals(qri.getSendResult())) {
                        msg++;
                    }
                    service.save(qri);
                }
                if (msg > 0) {
                    // 发送邮件提醒有重试次数超出5次的数据
                    SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 hh点");

                    sendMail(format.format(new Date()) + " 有" + msg + "条重发记录,重发次数超出5次,请跟踪问题!");
                }
                for (QmResendInfo qri : qriList) {
                    qri.setLockTask("unlock");
                }
                service.save(qriList);
                logger.info(MarkerConstant.QIMEN_MARKER, "奇门重发结束");
            }

        } catch (Exception e) {
            logger.error(MarkerConstant.QIMEN_MARKER, "CountWarehouseAgeTaskProvider case some error.", e);
        }
    }

    public void sendMail(String content) {
        // MailSenderInfo mailInfo = buildMailInfo(content);
        // SimpleMailSender.sendHtmlMail(mailInfo);
    }

    private MailSenderInfo buildMailInfo(String content) {
        MailSenderInfo mailInfo = new MailSenderInfo();

        mailInfo.setMailServerHost("smtp.exmail.qq.com");
        mailInfo.setMailServerPort("587");
        mailInfo.setValidate(true);

        mailInfo.setUserName("operation@paiu.com.cn");
        mailInfo.setPassword("paiu2014");

        mailInfo.setFromAddress("operation@paiu.com.cn");

        // String [] email =
        // {"hewuxiang@paiu.com.cn","caocao@paiu.com.cn","yanlei@paiu.com.cn","gaohuan@paiu.com.cn","chenyue@paiu.com.cn"};
        String[] email = { "gaohuan@paiu.com.cn" };
        mailInfo.setToAddress(email);
        // mailInfo.setCcAddress(new String[]{"chenyue@paiu.com.cn"});
        mailInfo.setSubject("【重要】奇门接口重发次数超出");
        mailInfo.setContent(content);
        return mailInfo;
    }

}
